from django.shortcuts import render, redirect, HttpResponse
from Oa_system.models import Staffing
from administrative.models import Company, User, Topicsattachments
from union_process.models import *
from django.views import View
import json, uuid, datetime, os, xlrd, re, urllib.parse, base64
from logistics.MessagePushOperationRecords import RecordAndPush
from announcements import public_file
from administrative.public_file import ParseWord, PDFConverter
from django.db.models import Q


class PrintingProcessListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'union_process/PrintingProcessList.html', {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = user.officialseal_set.all().order_by('-create_time')
        data_list = [{'id': obj.id, 'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"), 'reason': obj.reason, 'printing': obj.printing, 'file_type': obj.get_file_type(),
                      'use_seal': ','.join([i.seal_name for i in obj.use_seal.all()]), 'status': obj.get_state_str(), 'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='PrintingProcessDraft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
                      else f"<a href='PrintingProcessDetail.html?id={obj.id}'>查看</a> | <a href='PrintingProcessDetail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state not in ['draft', 'stop']
                      else f"<a href='PrintingProcessDetail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='PrintingProcessDetail.html?id={obj.id}'>查看</a>",
                      } for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PrintingProcessIndexView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        seal_obj = UnionSeal.objects.filter(status='1')
        return render(request, 'union_process/PrintingProcessIndex.html', {'realname': real_name, 'position': position, 'department': department, "uuid": uuid.uuid4(), "create_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), "seal_obj": seal_obj})

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        reason = request.POST.get("reason", "")
        printing = request.POST.get("printing", "")
        file_type = request.POST.get("file_type", "")
        use_seal = request.POST.get("use_seal_list", "")
        note = request.POST.get("note", "")
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "工会用印流程")
        except:
            pass

        if flow_id:
            obj = OfficialSeal.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.printing = printing
            obj.file_type = file_type
            obj.note = note
            obj.save()
            obj.current_audit_users.clear()
            obj.officialsealrecord_set.filter(state='unaudit').delete()
            message_str = "修改成功"
        else:
            obj = OfficialSeal.objects.create(apply_user=request.user, company=request.user.company, reason=reason, fj_number=fj_number, printing=printing, file_type=file_type, note=note)
            message_str = "创建成功"

        obj.use_seal.clear()
        for seal_id in json.loads(use_seal):
            obj.use_seal.add(UnionSeal.objects.get(id=int(seal_id)))


        flag = True
        one_step = request.user.company.head_people
        if request.user != one_step:
            OfficialSealRecord.objects.create(node='one', audit_note='', audit_people=one_step, parent_id=obj)
            obj.state = 'one'
            obj.current_audit_users.add(one_step)
            flag = False

        two_setp = Company.objects.get(id=7).head_people
        OfficialSealRecord.objects.create(node='two', audit_note='', audit_people=two_setp, parent_id=obj)
        if flag:
            obj.state = 'two'
            obj.current_audit_users.add(two_setp)

        if file_type == '1':
            three_setp = Company.objects.get(id=22).head_people
            OfficialSealRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=obj)

        four_setp = Staffing.objects.get(station='工会主席').post_personnel.all().first()
        OfficialSealRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=obj)

        OfficialSealRecord.objects.create(node='five', audit_note='', audit_people=two_setp, parent_id=obj)

        seven_setp = Staffing.objects.get(station='工会印章管理员').post_personnel.all().first()
        OfficialSealRecord.objects.create(node='six', audit_note='', audit_people=seven_setp, parent_id=obj)

        obj.save()
        returnDict = {'status': 'success', 'message': message_str, 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PrintingProcessDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        obj = OfficialSeal.objects.get(id=flow_id)
        seal_obj = UnionSeal.objects.filter(status='1')
        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, "file_list": file_list, "seal_list": [i.id for i in obj.use_seal.all()], "seal_obj": seal_obj, "create_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M")}
        return render(request, 'union_process/PrintingProcessDraft.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        reason = request.POST.get("reason", "")
        printing = request.POST.get("printing", "")
        file_type = request.POST.get("file_type", "")
        use_seal = request.POST.get("use_seal_list", "")
        note = request.POST.get("note", "")

        if flow_id:
            obj = OfficialSeal.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.printing = printing
            obj.file_type = file_type
            obj.note = note
            obj.save()
            message_str = "修改成功"
        else:
            obj = OfficialSeal.objects.create(apply_user=request.user, company=request.user.company, reason=reason, fj_number=fj_number, printing=printing, file_type=file_type, note=note)
            message_str = "创建成功"

        obj.use_seal.clear()
        for seal_id in json.loads(use_seal):
            obj.use_seal.add(UnionSeal.objects.get(id=int(seal_id)))

        obj.state = 'draft'
        obj.save()
        returnDict = {'status': 'success', 'message': message_str, 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PrintingProcessDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = OfficialSeal.objects.get(id=flow_id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.officialsealrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.officialsealrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                     'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                     'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_type": atta_obj.file_type,
                      "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        seal_obj = UnionSeal.objects.filter(status='1')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (obj.state == 'refuse' and obj.apply_user == request.user) or revise else 'false', 'flow_dict': flow_dict, "revise": revise, "seal_list": [i.id for i in obj.use_seal.all()],
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user == obj.apply_user else 'false', "seal_obj": seal_obj, "seal_name_list": ",".join([i.seal_name for i in obj.use_seal.all()]),
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'union_process/PrintingProcessDetai.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "工会用印流程")
        except:
            pass
        obj = OfficialSeal.objects.get(id=int(flow_id))

        if not obj.officialsealrecord_set.filter(node=obj.state, state='unaudit', audit_people=request.user).count():
            returnData = {'code': 400, 'message': '该流程已审核，请勿重复点击！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.officialsealrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.officialsealrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.officialsealrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                if obj.officialsealrecord_set.filter(node='three').count():
                    next_audit_record = obj.officialsealrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                else:
                    next_audit_record = obj.officialsealrecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.officialsealrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    next_audit_record = obj.officialsealrecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.officialsealrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    next_audit_record = obj.officialsealrecord_set.filter(node='five', state='unaudit').first()
                    obj_state = 'five'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.officialsealrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    next_audit_record = obj.officialsealrecord_set.filter(node='six', state='unaudit').first()
                    obj_state = 'six'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'six':
            audit_record = obj.officialsealrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    obj_state = 'end'
                    file_lenth = request.POST.get('file_lenth', '')
                    for i in range(int(file_lenth)):
                        files = request.FILES.get(f'file{i}')
                        file_obj = Topicsattachments.objects.create(
                            topics_number=obj.fj_number, file_size=public_file.StrOfSize(files.size), file_path=files,
                            uploader=request.user.username,
                            uploader_user=request.user, file_type=1, is_deleted=False, source='LZSQ'
                        )
                        sys_path = os.getcwd()
                        file_name = files.name
                        file_obj.file_name = file_name
                        file_obj.save()

                        word_path = sys_path + '/media/' + str(file_obj.file_path)
                        old_word_path = word_path
                        temp_name = os.path.splitext(file_name)[0]
                        new_word_path = old_word_path.replace(
                            os.path.splitext(file_obj.file_path.name.split("/")[-1])[0], temp_name)
                        os.rename(old_word_path, new_word_path)
                        word_path = new_word_path

                        file_path = file_obj.file_path.name.replace(
                            os.path.splitext(file_obj.file_path.name.split("/")[-1])[0], temp_name)

                        if word_path.split('.')[-1] in ['docx', 'doc', 'DOC', 'DOCX']:
                            pdf_path = ParseWord().word2pdf(word_path)
                        elif word_path.split(".")[-1] in ['ppt', 'pptx']:
                            pdf_path = ParseWord().ppt2pdf(word_path)
                        elif word_path.split(".")[-1] in ['xls', 'xlsx', 'XLS', 'XLSX']:
                            b = xlrd.open_workbook(word_path)
                            sheetnum = len(b.sheets())
                            pdfConverter = PDFConverter(word_path, sheetnum, os.path.splitext(file_name)[0])
                            pdf_path = pdfConverter.run_conver()
                        else:
                            pdf_path = '/media/' + str(file_path)
                        pdf_list = []
                        if type(pdf_path) is list:
                            for i in range(len(pdf_path)):
                                if i == 0:
                                    file_obj.pdf_path = pdf_path[i].replace(os.getcwd(), '')
                                    tic_id = file_obj.id
                                    file_obj.save()
                                else:
                                    all_file = Topicsattachments.objects.create(topics_number=obj.fj_number, file_path=files, file_size=public_file.StrOfSize(files.size), uploader=request.user.username,
                                        file_type=1, pdf_path=pdf_path[i].replace(os.getcwd(), ''), file_name=os.path.split(pdf_path[i])[1], source="LZSQ", uploader_user=request.user.username
                                    )
                                    tic_id = all_file.id
                                one_dict = {"id": tic_id, 'pdf_path': pdf_path[i].replace(os.getcwd(), '')}
                                pdf_list.append(one_dict)
                        else:
                            fileName = pdf_path.split("/")[-1].split(".")[0]
                            pdf_path = pdf_path.replace(fileName, files.name.split(".")[0]).replace(os.getcwd(), "")
                            pdf_path = pdf_path.replace(os.path.splitext(os.path.split(pdf_path)[1])[0], os.path.splitext(file_name)[0])
                            file_obj.pdf_path = pdf_path
                            file_obj.save()
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "工会用印申请"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class PrintingProcessStop(View):
    def post(self, request):
        flow_id = request.POST.get('id', '')
        types = request.POST.get('types', '')
        obj = OfficialSeal.objects.get(id=int(flow_id))
        if obj.state == 'end':
            returnData = {'code': 500, 'message': '操作失败，已完结流程无法操作！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.current_audit_users.clear()
        if types == 'stop':
            obj.state = 'stop'
            obj.save()
            returnData = {'code': 200, 'message': '终止成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            Topicsattachments.objects.filter(topics_number=obj.fj_number).delete()
            obj.officialsealrecord_set.all().delete()
            obj.audit_users_already.clear()
            obj.delete()
            returnData = {'code': 200, 'message': '删除成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class EconomicSigningListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'union_process/EconomicSigningList.html', {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = user.economiccountersign_set.all().order_by('-create_time')
        data_list = [{'id': obj.id, 'contract_name': obj.contract_name, 'project_company': obj.project_company.name if obj.project_company else "", 'contract_number': obj.contract_number, 'other_unit': obj.other_unit,
                      'contract_money': obj.contract_money, 'status': obj.get_state_str(), 'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='EconomicSigningDraft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
                      else f"<a href='EconomicSigningDetail.html?id={obj.id}'>查看</a> | <a href='EconomicSigningDetail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state not in ['draft', 'stop']
                      else f"<a href='EconomicSigningDetail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='EconomicSigningDetail.html?id={obj.id}'>查看</a>",
                      } for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class EconomicSigningIndexView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        returndata = Company.objects.filter(~Q(id=87)).order_by("serial_number")
        company_list, ComList = [], []
        for c in returndata:
            if c.name not in ComList:
                one_dict = {"id": c.id, "name": c.name}
                company_list.append(one_dict)
                ComList.append(c.name)
        return render(request, 'union_process/EconomicSigningIndex.html', {'realname': real_name, 'position': position, 'department': department, "uuid": uuid.uuid4(),
                                                                           "create_time": datetime.datetime.now().strftime("%Y-%m-%d"), "company_list": company_list})

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        project_company = request.POST.get("project_company", "")           # 立项科室
        other_unit = request.POST.get("other_unit", "")             # 对方单位
        contract_name = request.POST.get("contract_name", "")       # 合同名称
        contract_number = request.POST.get("contract_number", "")       # 合同编号
        contract_money = request.POST.get("contract_money", "")  # 合同金额
        money_capital = request.POST.get("money_capital", "")  # 合同金额大写
        main_terms = request.POST.get("main_terms", "")  # 合同内容主要条款
        note = request.POST.get("note", "")  # 合同内容主要条款
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "工会合同会签流程")
        except:
            pass

        if flow_id:
            obj = EconomicCountersign.objects.get(id=int(flow_id))
            Topicsattachments.objects.filter(topics_number=obj.fj_number).delete()
            obj.current_audit_users.clear()
            obj.economiccountersignrecord_set.filter(state='unaudit').delete()
            message_str = "修改成功"
        else:
            obj = EconomicCountersign.objects.create(apply_user=request.user, company=request.user.company, other_unit=other_unit, fj_number=fj_number, contract_name=contract_name, contract_number=contract_number,
                                                     note=note, contract_money=contract_money, money_capital=money_capital, main_terms=main_terms)
            message_str = "创建成功"

        one_step = Company.objects.get(id=7).head_people
        EconomicCountersignRecord.objects.create(node='one', audit_note='', audit_people=one_step, parent_id=obj)
        obj.state = 'one'
        obj.current_audit_users.add(one_step)

        two_setp = Company.objects.get(id=23).head_people
        EconomicCountersignRecord.objects.create(node='two', audit_note='', audit_people=two_setp, parent_id=obj)

        three_setp = Company.objects.get(id=18).head_people
        EconomicCountersignRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=obj)

        four_setp = Company.objects.get(id=22).head_people
        EconomicCountersignRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=obj)

        five_setp = Staffing.objects.get(station='工会主席').post_personnel.all().first()
        EconomicCountersignRecord.objects.create(node='five', audit_note='', audit_people=five_setp, parent_id=obj)

        seven_setp = Company.objects.get(id=7).head_people
        EconomicCountersignRecord.objects.create(node='six', audit_note='', audit_people=seven_setp, parent_id=obj)

        eight_setp = Staffing.objects.get(station='工会印章管理员').post_personnel.all().first()
        EconomicCountersignRecord.objects.create(node='seven', audit_note='', audit_people=eight_setp, parent_id=obj)
        obj.save()
        returnDict = {'status': 'success', 'message': message_str, 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class EconomicSigningDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        obj = EconomicCountersign.objects.get(id=flow_id)
        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        returndata = Company.objects.filter(~Q(id=87)).order_by("serial_number")
        company_list, ComList = [], []
        for c in returndata:
            if c.name not in ComList:
                one_dict = {"id": c.id, "name": c.name}
                company_list.append(one_dict)
                ComList.append(c.name)
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, "file_list": file_list, "company_list": company_list, "create_time": datetime.datetime.now().strftime("%Y-%m-%d")}
        return render(request, 'union_process/EconomicSigningDraft.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        project_company = request.POST.get("project_company", "")           # 立项科室
        other_unit = request.POST.get("other_unit", "")             # 对方单位
        contract_name = request.POST.get("contract_name", "")       # 合同名称
        contract_number = request.POST.get("contract_number", "")       # 合同编号
        contract_money = request.POST.get("contract_money", "")  # 合同金额
        money_capital = request.POST.get("money_capital", "")  # 合同金额大写
        main_terms = request.POST.get("main_terms", "")  # 合同内容主要条款
        note = request.POST.get("note", "")  # 合同内容主要条款
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "工会合同会签流程")
        except:
            pass

        if flow_id:
            obj = EconomicCountersign.objects.get(id=int(flow_id))
            obj.other_unit = other_unit
            obj.contract_name = contract_name
            obj.contract_number = contract_number
            obj.contract_money = contract_money
            obj.money_capital = money_capital
            obj.main_terms = main_terms
            obj.note = note
            obj.save()
            obj.current_audit_users.clear()
            obj.economiccountersignrecord_set.filter(state='unaudit').delete()
            message_str = "修改成功"
        else:
            obj = EconomicCountersign.objects.create(apply_user=request.user, company=request.user.company, other_unit=other_unit, fj_number=fj_number, contract_name=contract_name, contract_number=contract_number,
                                                     note=note, contract_money=contract_money, money_capital=money_capital, main_terms=main_terms)
            message_str = "创建成功"

        if project_company:
            project_company_list = re.findall('\((.*?)\)', project_company)
            dep_obj = Company.objects.get(id=int(project_company_list[0]))
            obj.project_company = dep_obj
        obj.state = 'draft'
        obj.save()
        returnDict = {'status': 'success', 'message': message_str, 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


def trade_union_upload_file(request, obj, file_type):
    file_lenth = request.POST.get('file_lenth', '')
    for i in range(int(file_lenth)):
        files = request.FILES.get(f'file{i}')
        file_obj = Topicsattachments.objects.create(
            topics_number=obj.fj_number, file_size=public_file.StrOfSize(files.size), file_path=files, uploader=request.user.username,
            uploader_user=request.user, file_type=file_type, is_deleted=False, source='LZSQ'
        )
        sys_path = os.getcwd()
        file_name = files.name
        file_obj.file_name = file_name
        file_obj.save()

        word_path = sys_path + '/media/' + str(file_obj.file_path)
        old_word_path = word_path
        temp_name = os.path.splitext(file_name)[0]
        new_word_path = old_word_path.replace(
            os.path.splitext(file_obj.file_path.name.split("/")[-1])[0], temp_name)
        os.rename(old_word_path, new_word_path)
        word_path = new_word_path

        file_path = file_obj.file_path.name.replace(
            os.path.splitext(file_obj.file_path.name.split("/")[-1])[0], temp_name)

        if word_path.split('.')[-1] in ['docx', 'doc', 'DOC', 'DOCX']:
            pdf_path = ParseWord().word2pdf(word_path)
        elif word_path.split(".")[-1] in ['ppt', 'pptx']:
            pdf_path = ParseWord().ppt2pdf(word_path)
        elif word_path.split(".")[-1] in ['xls', 'xlsx', 'XLS', 'XLSX']:
            b = xlrd.open_workbook(word_path)
            sheetnum = len(b.sheets())
            pdfConverter = PDFConverter(word_path, sheetnum, os.path.splitext(file_name)[0])
            pdf_path = pdfConverter.run_conver()
        else:
            pdf_path = '/media/' + str(file_path)
        pdf_list = []
        if type(pdf_path) is list:
            for i in range(len(pdf_path)):
                if i == 0:
                    file_obj.pdf_path = pdf_path[i].replace(os.getcwd(), '')
                    tic_id = file_obj.id
                    file_obj.save()
                else:
                    all_file = Topicsattachments.objects.create(topics_number=obj.fj_number, file_path=files, file_size=public_file.StrOfSize(files.size),
                                                                uploader=request.user.username, file_type=1, pdf_path=pdf_path[i].replace(os.getcwd(), ''),
                                                                file_name=os.path.split(pdf_path[i])[1], source="LZSQ", uploader_user=request.user.username)
                    tic_id = all_file.id
                one_dict = {"id": tic_id, 'pdf_path': pdf_path[i].replace(os.getcwd(), '')}
                pdf_list.append(one_dict)
        else:
            fileName = pdf_path.split("/")[-1].split(".")[0]
            pdf_path = pdf_path.replace(fileName, files.name.split(".")[0]).replace(os.getcwd(), "")
            pdf_path = pdf_path.replace(os.path.splitext(os.path.split(pdf_path)[1])[0], os.path.splitext(file_name)[0])
            file_obj.pdf_path = pdf_path
            file_obj.save()


class EconomicSigningDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = EconomicCountersign.objects.get(id=flow_id)
        if obj.topics_id:
            audit_dic = {}
            topics_obj = obj.topics_id
            for audit_obj in topics_obj.topicsauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
            main_file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"), "pdf_path": atta_obj.pdf_path, "file_type": "0",
                "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                "upload_time": str(atta_obj.create_time).split(".")[0][:-3], "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=topics_obj.uuid, file_type="0")
            ]

            file_flag = "false"

            xiugai_list = []
            for iiii in Topicsattachments.objects.filter(topics_number=obj.fj_number):
                if iiii.file_type == '1':
                    file_flag = "true"
                xiugai_list.append(
                    {"file_name": iiii.file_name if iiii.file_name else iiii.file_path.name.split('/')[-1],
                     "file_path": iiii.pdf_path.replace("\\", "/"), "pdf_path": iiii.pdf_path,
                     "file_type": iiii.file_type,
                     "word_path": iiii.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": iiii.file_size,
                     "uploader": iiii.uploader_user.real_name, "upload_time": str(iiii.create_time).split(".")[0][:-3],
                     "id": iiii.id}
                )
                main_file_list.append(
                    {"file_name": iiii.file_name if iiii.file_name else iiii.file_path.name.split('/')[-1], "file_path": iiii.pdf_path.replace("\\", "/"), "pdf_path": iiii.pdf_path, "file_type": iiii.file_type,
                     "word_path": iiii.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": iiii.file_size, "uploader": iiii.uploader_user.real_name, "upload_time": str(iiii.create_time).split(".")[0][:-3], "id": iiii.id}
                )

            topic_audit_dic, topic_flow_dict = {}, {}
            for audit_obj in obj.economiccountersignrecord_set.all():
                if audit_obj.node in topic_audit_dic:
                    topic_audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                                                            'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                            'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in obj.economiccountersignrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    topic_flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in topic_flow_dict]) + 1}
                    topic_audit_dic[audit_obj.node] = [
                        {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                         'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                         'audit_note': audit_obj.audit_note,
                         'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                         'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            help_department = ' ,'.join([i.name for i in topics_obj.help_department.all()])
            help_department1 = ' ,'.join([f"{i.name}({i.id})" for i in topics_obj.help_department.all()])
            if Topicsattachments.objects.filter(topics_number=topics_obj.uuid):
                file_path = Topicsattachments.objects.filter(topics_number=topics_obj.uuid).first().pdf_path.replace("\\", "/")
            elif Topicsattachments.objects.filter(topics_number=obj.fj_number):
                file_path = Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/")
            else:
                file_path = ""
            gh_leader = Company.objects.get(id=7).head_people
            data_dic = {'realname': real_name, 'position': request.user.post, 'department': request.user.company.name,
                        'apply_user': topics_obj.employee.real_name, 'state': topics_obj.get_state_display(),
                        'main_file_list': main_file_list, 'number': topics_obj.number, "xiugai_list": xiugai_list,
                        'topics_name': topics_obj.topics_name, 'FundingSource': topics_obj.get_funding_source(),
                        'topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_text).decode()).decode()),
                        'topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_basis).decode()).decode()),
                        'solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.solution).decode()).decode()) if topics_obj.solution != "空" else "",
                        'db_topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_topics_text).decode()).decode()) if topics_obj.db_topics_text else "",
                        'db_topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_topics_basis).decode()).decode()) if topics_obj.db_topics_basis else "",
                        'db_solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_solution).decode()).decode()) if topics_obj.db_solution else "",
                        'topics_estimate': topics_obj.topics_estimate, 'help_department': help_department, 'help_department1': help_department1, "file_flag": file_flag,
                        'jfly': topics_obj.jfly if topics_obj.jfly else "", 'ysje': topics_obj.ysje if topics_obj.ysje else "", "uuid": uuid.uuid4(),
                        'audit_list': audit_dic, "topic_audit_dic": topic_audit_dic, "topic_flow_dict": topic_flow_dict, "obj": topics_obj, "flow_obj": obj,
                        'is_edit': 'true' if (obj.state == 'refuse' and gh_leader == request.user) or revise else 'false',
                        'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', "six", "seven"] and request.user in obj.current_audit_users.all() else 'false',
                        'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', "seven", "refuse"] and request.user == obj.apply_user else 'false',
                        'file_path': file_path}
            return render(request, 'union_process/EconomicSigningDetailTransfer.html', data_dic)
        else:
            audit_dic, flow_dict = {}, {}
            for audit_obj in obj.economiccountersignrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append(
                        {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                         'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                         'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                         'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in obj.economiccountersignrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                    audit_dic[audit_obj.node] = [
                        {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                         'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                         'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                         'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                          "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_type": atta_obj.file_type,
                          "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                          "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
            returndata = Company.objects.filter(~Q(id=87)).order_by("serial_number")
            company_list, ComList = [], []
            for c in returndata:
                if c.name not in ComList:
                    one_dict = {"id": c.id, "name": c.name}
                    company_list.append(one_dict)
                    ComList.append(c.name)
            context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                       "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                       'is_edit': 'true' if (obj.state == 'refuse' and obj.apply_user == request.user) or revise else 'false',
                       'flow_dict': flow_dict, "revise": revise, "company_list": company_list,
                       'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'] and request.user in obj.current_audit_users.all() else 'false',
                       'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'] and request.user == obj.apply_user else 'false',
                       'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                       }
            return render(request, 'union_process/EconomicSigningDetail.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "工会经济合同会签")
        except:
            pass
        obj = EconomicCountersign.objects.get(id=int(flow_id))
        gh_leader = Company.objects.get(id=7).head_people
        if not obj.economiccountersignrecord_set.filter(node=obj.state, state='unaudit', audit_people=request.user).count():
            returnData = {'code': 400, 'message': '该流程已审核，请勿重复点击！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.economiccountersignrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                trade_union_upload_file(request, obj, 0)
                next_audit_record = obj.economiccountersignrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(gh_leader)

        elif obj.state == 'two':
            audit_record = obj.economiccountersignrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                if obj.economiccountersignrecord_set.filter(node='three').count():
                    next_audit_record = obj.economiccountersignrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                else:
                    next_audit_record = obj.economiccountersignrecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(gh_leader)

        elif obj.state == 'three':
            audit_record = obj.economiccountersignrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    next_audit_record = obj.economiccountersignrecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(gh_leader)

        elif obj.state == 'four':
            audit_record = obj.economiccountersignrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    next_audit_record = obj.economiccountersignrecord_set.filter(node='five', state='unaudit').first()
                    obj_state = 'five'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(gh_leader)

        elif obj.state == 'five':
            audit_record = obj.economiccountersignrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    next_audit_record = obj.economiccountersignrecord_set.filter(node='six', state='unaudit').first()
                    obj_state = 'six'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(gh_leader)

        elif obj.state == 'six':
            audit_record = obj.economiccountersignrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    next_audit_record = obj.economiccountersignrecord_set.filter(node='seven', state='unaudit').first()
                    obj_state = 'seven'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(gh_leader)

        elif obj.state == 'seven':
            audit_record = obj.economiccountersignrecord_set.filter(node='seven', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    obj_state = 'end'
                    trade_union_upload_file(request, obj, 1)
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(gh_leader)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "工会用印申请"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.contract_name[:15] + "……" if len(obj.contract_name) > 15 else obj.contract_name
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class EconomicSigningStopView(View):
    def post(self, request):
        flow_id = request.POST.get('id', '')
        types = request.POST.get('types', '')
        obj = EconomicCountersign.objects.get(id=int(flow_id))
        if obj.state == 'end':
            returnData = {'code': 500, 'message': '操作失败，已完结流程无法操作！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.current_audit_users.clear()
        if types == 'stop':
            obj.state = 'stop'
            obj.save()
            returnData = {'code': 200, 'message': '终止成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            Topicsattachments.objects.filter(topics_number=obj.fj_number).delete()
            obj.economiccountersignrecord_set.all().delete()
            obj.audit_users_already.clear()
            obj.delete()
            returnData = {'code': 200, 'message': '删除成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class PayFlowListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'union_process/PayFlowList.html', {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = user.paymentprocess_set.all().order_by('-create_time')
        data_list = [{'id': obj.id, 'reason': obj.reason, 'payee': obj.payee, 'total_amount': obj.total_amount, 'source': obj.get_source_str(),
                      'pay_type': obj.get_pay_type(), 'status': obj.get_state_str(), 'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='PayFlowDraft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
                      else f"<a href='PayFlowDetail.html?id={obj.id}'>查看</a> | <a href='PayFlowDetail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state not in ['draft', 'stop']
                      else f"<a href='PayFlowDetail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='PayFlowDetail.html?id={obj.id}'>查看</a>",
                      } for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PayFlowIndexView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'union_process/PayFlowIndex.html', {'realname': real_name, 'position': position, 'department': department, "uuid": uuid.uuid4()})

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        reason = request.POST.get("reason", "")           # 付款事由
        source = request.POST.get("source", "")             # 经费来源
        bank = request.POST.get("bank", "")       # 开户行
        pay_type = request.POST.get("pay_type", "")       # 付款类型
        total_amount = request.POST.get("total_amount", "")  # 总金额
        money_capital = request.POST.get("money_capital", "")  # 合同金额大写
        payee = request.POST.get("payee", "")  # 收款单位
        account_number = request.POST.get("account_number", "")  # 收款单位
        note = request.POST.get("note", "")
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "工会付款流程")
        except:
            pass

        if flow_id:
            obj = PaymentProcess.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.source = source
            obj.payee = payee
            obj.account_number = account_number
            obj.money_capital = money_capital
            obj.total_amount = total_amount
            obj.pay_type = pay_type
            obj.bank = bank
            obj.note = note
            obj.save()
            obj.current_audit_users.clear()
            obj.paymentprocessrecord_set.filter(state='unaudit').delete()
            message_str = "修改成功"
        else:
            obj = PaymentProcess.objects.create(apply_user=request.user, company=request.user.company, reason=reason, fj_number=fj_number, source=source, payee=payee, bank=bank,
                                                     note=note, account_number=account_number, money_capital=money_capital, total_amount=total_amount, pay_type=pay_type)
            message_str = "创建成功"

        flag = True
        two_setp = Company.objects.get(id=7).head_people
        PaymentProcessRecord.objects.create(node='two', audit_note='', audit_people=two_setp, parent_id=obj)
        if flag:
            obj.state = 'two'
            obj.current_audit_users.add(two_setp)

        three_setp = Staffing.objects.get(station='工会会计').post_personnel.all().first()
        PaymentProcessRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=obj)

        four_setp = Company.objects.get(id=23).head_people
        PaymentProcessRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=obj)

        five_setp = Staffing.objects.get(station='工会主席').post_personnel.all().first()
        PaymentProcessRecord.objects.create(node='five', audit_note='', audit_people=five_setp, parent_id=obj)

        six_setp = Staffing.objects.get(station='工会经费支付').post_personnel.all().first()
        PaymentProcessRecord.objects.create(node='six', audit_note='', audit_people=six_setp, parent_id=obj)

        obj.save()
        returnDict = {'status': 'success', 'message': message_str, 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PayFlowDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        obj = PaymentProcess.objects.get(id=flow_id)
        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, "file_list": file_list}
        return render(request, 'union_process/PayFlowDraft.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        reason = request.POST.get("reason", "")  # 付款事由
        source = request.POST.get("source", "")  # 经费来源
        bank = request.POST.get("bank", "")  # 开户行
        pay_type = request.POST.get("pay_type", "")  # 付款类型
        total_amount = request.POST.get("total_amount", "")  # 总金额
        money_capital = request.POST.get("money_capital", "")  # 合同金额大写
        payee = request.POST.get("payee", "")  # 收款单位
        account_number = request.POST.get("account_number", "")  # 收款单位
        note = request.POST.get("note", "")
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "工会付款流程")
        except:
            pass

        if flow_id:
            obj = PaymentProcess.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.source = source
            obj.payee = payee
            obj.account_number = account_number
            obj.money_capital = money_capital
            obj.total_amount = total_amount
            obj.pay_type = pay_type
            obj.bank = bank
            obj.note = note
            obj.save()
            message_str = "修改成功"
        else:
            obj = PaymentProcess.objects.create(apply_user=request.user, company=request.user.company, reason=reason, fj_number=fj_number, source=source, payee=payee, bank=bank,
                                                note=note, account_number=account_number, money_capital=money_capital, total_amount=total_amount, pay_type=pay_type)
            message_str = "创建成功"

        obj.state = 'draft'
        obj.save()
        returnDict = {'status': 'success', 'message': message_str, 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PayFlowDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = PaymentProcess.objects.get(id=flow_id)
        if obj.topics_id:
            audit_dic = {}
            topics_obj = obj.topics_id
            for audit_obj in topics_obj.topicsauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state, 'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
            main_file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "pdf_path": atta_obj.pdf_path,
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=topics_obj.uuid, file_type="0")]
            flow_file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "pdf_path": atta_obj.pdf_path, "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)
            ]
            topic_audit_dic, topic_flow_dict = {}, {}
            for audit_obj in obj.paymentprocessrecord_set.all():
                if audit_obj.node in topic_audit_dic:
                    topic_audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in obj.paymentprocessrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    topic_flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in topic_flow_dict]) + 1}
                    topic_audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            help_department = ' ,'.join([i.name for i in topics_obj.help_department.all()])
            help_department1 = ' ,'.join([f"{i.name}({i.id})" for i in topics_obj.help_department.all()])

            received_audit_dic, company_type = {}, ''
            if topics_obj.received_foreign:
                received_obj = topics_obj.received_foreign
                company_type = "yb" if topics_obj.received_foreign.apply_user.company.id == 80 else "db"
                for audit_obj in received_obj.officialdocumentsauditrecord_set.all():
                    if audit_obj.node in received_audit_dic:
                        received_audit_dic[audit_obj.node].append(
                            {'audit_user': audit_obj.audit_people.real_name,
                             'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                             'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                             'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                             'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                    else:
                        received_audit_dic[audit_obj.node] = [
                            {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                             'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                             'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                             'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            data_dic = {'realname': real_name, 'position': request.user.post, 'department': request.user.company.name, 'apply_user': topics_obj.employee.real_name, 'state': topics_obj.get_state_display(),
                        'main_file_list': main_file_list+flow_file_list, 'number': topics_obj.number, 'topics_name': topics_obj.topics_name, "flow_file_list": flow_file_list,
                        'topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_text).decode()).decode()),
                        'topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_basis).decode()).decode()),
                        'solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.solution).decode()).decode()) if topics_obj.solution != "空" else "",
                        'db_topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_topics_text).decode()).decode()) if topics_obj.db_topics_text else "",
                        'db_topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_topics_basis).decode()).decode()) if topics_obj.db_topics_basis else "",
                        'db_solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_solution).decode()).decode()) if topics_obj.db_solution else "",
                        'topics_estimate': topics_obj.topics_estimate, 'help_department': help_department, 'help_department1': help_department1,
                        'jfly': topics_obj.jfly if topics_obj.jfly else "", 'ysje': topics_obj.ysje if topics_obj.ysje else "", 'uuid': obj.fj_number,
                        'audit_list': audit_dic, "topic_audit_dic": topic_audit_dic, "topic_flow_dict": topic_flow_dict, "obj": topics_obj, "flow_obj": obj,
                        "is_refer": 'true' if obj.state == 'zero' else 'false', 'received_audit_dic': received_audit_dic, 'company_type': company_type,
                        'is_edit': 'true' if (obj.state == 'refuse' and obj.apply_user == request.user) or revise else 'false',
                        'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] and request.user in obj.current_audit_users.all() else 'false',
                        'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] and request.user == obj.apply_user else 'false',
                        'file_path': Topicsattachments.objects.filter(topics_number=topics_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=topics_obj.uuid) else ''}
            return render(request, 'union_process/PayFlowDetailTransfer.html', data_dic)
        else:
            audit_dic, flow_dict = {}, {}
            for audit_obj in obj.paymentprocessrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append(
                        {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                         'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                         'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                         'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in obj.paymentprocessrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                    audit_dic[audit_obj.node] = [
                        {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                         'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                         'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                         'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                          "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_type": atta_obj.file_type,
                          "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                          "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
            context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                       'is_edit': 'true' if (obj.state == 'refuse' and obj.apply_user == request.user) or revise else 'false', 'flow_dict': flow_dict, "revise": revise,
                       'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] and request.user in obj.current_audit_users.all() else 'false',
                       'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] and request.user == obj.apply_user else 'false',
                       'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                       }
            return render(request, 'union_process/PayFlowDetail.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "工会付款流程")
        except:
            pass
        obj = PaymentProcess.objects.get(id=int(flow_id))

        if not obj.paymentprocessrecord_set.filter(node=obj.state, state='unaudit', audit_people=request.user).count():
            returnData = {'code': 400, 'message': '该流程已审核，请勿重复点击！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.paymentprocessrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.paymentprocessrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.paymentprocessrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.paymentprocessrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.paymentprocessrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    next_audit_record = obj.paymentprocessrecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.paymentprocessrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    next_audit_record = obj.paymentprocessrecord_set.filter(node='five', state='unaudit').first()
                    obj_state = 'five'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.paymentprocessrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    next_audit_record = obj.paymentprocessrecord_set.filter(node='six', state='unaudit').first()
                    obj_state = 'six'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'six':
            audit_record = obj.paymentprocessrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    obj_state = 'end'
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "工会付款流程"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class PayFlowStopView(View):
    def post(self, request):
        flow_id = request.POST.get('id', '')
        types = request.POST.get('types', '')
        obj = PaymentProcess.objects.get(id=int(flow_id))
        if obj.state == 'end':
            returnData = {'code': 500, 'message': '操作失败，已完结流程无法操作！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.current_audit_users.clear()
        if types == 'stop':
            obj.state = 'stop'
            obj.save()
            returnData = {'code': 200, 'message': '终止成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            Topicsattachments.objects.filter(topics_number=obj.fj_number).delete()
            obj.paymentprocessrecord_set.all().delete()
            obj.audit_users_already.clear()
            obj.delete()
            returnData = {'code': 200, 'message': '删除成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class PreApprovalListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'union_process/PreApprovalList.html', {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = user.eventapproval_set.all().order_by('-create_time')
        data_list = [{'id': obj.id, 'reason': obj.reason, 'venue': obj.venue, 'start_time': obj.start_time, 'end_time': obj.end_time,
                      'status': obj.get_state_str(), 'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='PreApprovalDraft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
                      else f"<a href='PreApprovalDetail.html?id={obj.id}'>查看</a> | <a href='PreApprovalDetail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state not in ['draft', 'stop']
                      else f"<a href='PreApprovalDetail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='PreApprovalDetail.html?id={obj.id}'>查看</a>",
                      } for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PreApprovalIndexView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'union_process/PreApprovalIndex.html', {'realname': real_name, 'position': position, 'department': department, "uuid": uuid.uuid4(),
                                                                       "create_time": datetime.datetime.now().strftime("%Y-%m-%d")})

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        reason = request.POST.get("reason", "")           # 活动事由
        venue = request.POST.get("venue", "")             # 活动地点
        start_time = request.POST.get("start_time", "")       # 开始时间
        end_time = request.POST.get("end_time", "")       # 结束时间
        participants = request.POST.get("participants", "")  # 参与人员
        additional = request.POST.get("additional", "")  # 是否补录
        note = request.POST.get("note", "")
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "工会活动审批")
        except:
            pass

        if flow_id:
            obj = EventApproval.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.venue = venue
            obj.start_time = start_time
            obj.end_time = end_time
            obj.note = note
            obj.additional = additional
            obj.participants = participants
            obj.save()
            obj.current_audit_users.clear()
            obj.eventapprovalrecord_set.filter(state='unaudit').delete()
            message_str = "修改成功"
        else:
            obj = EventApproval.objects.create(apply_user=request.user, company=request.user.company, fj_number=fj_number, reason=reason, venue=venue, start_time=start_time, note=note,
                                               end_time=end_time, additional=additional, participants=participants)
            message_str = "创建成功"

        flag = True
        one_step = request.user.company.head_people
        if request.user != one_step:
            EventApprovalRecord.objects.create(node='one', audit_note='', audit_people=one_step, parent_id=obj)
            obj.state = 'one'
            obj.current_audit_users.add(one_step)
            flag = False

        two_setp = request.user.company.leaders_id
        EventApprovalRecord.objects.create(node='two', audit_note='', audit_people=two_setp, parent_id=obj)
        if flag:
            obj.state = 'two'
            obj.current_audit_users.add(two_setp)

        three_setp = Company.objects.get(id=7).head_people
        EventApprovalRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=obj)

        four_setp = Staffing.objects.get(station='工会主席').post_personnel.all().first()
        EventApprovalRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=obj)

        six_setp = Company.objects.get(id=7).head_people
        EventApprovalRecord.objects.create(node='five', audit_note='', audit_people=six_setp, parent_id=obj)

        obj.save()
        returnDict = {'status': 'success', 'message': message_str, 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PreApprovalDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        obj = EventApproval.objects.get(id=flow_id)
        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, "file_list": file_list, "create_time": datetime.datetime.now().strftime("%Y-%m-%d")}
        return render(request, 'union_process/PreApprovalDraft.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        reason = request.POST.get("reason", "")  # 活动事由
        venue = request.POST.get("venue", "")  # 活动地点
        start_time = request.POST.get("start_time", "")  # 开始时间
        end_time = request.POST.get("end_time", "")  # 结束时间
        participants = request.POST.get("participants", "")  # 参与人员
        additional = request.POST.get("additional", "")  # 是否补录
        note = request.POST.get("note", "")
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "工会活动审批")
        except:
            pass

        if flow_id:
            obj = EventApproval.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.venue = venue
            obj.start_time = start_time
            obj.end_time = end_time
            obj.note = note
            obj.additional = additional
            obj.participants = participants
            obj.save()
            obj.current_audit_users.clear()
            obj.eventapprovalrecord_set.filter(state='unaudit').delete()
            message_str = "修改成功"
        else:
            obj = EventApproval.objects.create(apply_user=request.user, company=request.user.company, fj_number=fj_number, reason=reason, venue=venue, start_time=start_time, note=note,
                                               end_time=end_time, additional=additional, participants=participants)
            message_str = "创建成功"

        obj.state = 'draft'
        obj.save()
        returnDict = {'status': 'success', 'message': message_str, 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PreApprovalDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = EventApproval.objects.get(id=flow_id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.eventapprovalrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.eventapprovalrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                     'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                     'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_type": atta_obj.file_type,
                      "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (obj.state == 'refuse' and obj.apply_user == request.user) or revise else 'false', 'flow_dict': flow_dict, "revise": revise,
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user == obj.apply_user else 'false',
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'union_process/PreApprovalDetail.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "工会活动审批")
        except:
            pass
        obj = EventApproval.objects.get(id=int(flow_id))

        if not obj.eventapprovalrecord_set.filter(node=obj.state, state='unaudit', audit_people=request.user).count():
            returnData = {'code': 400, 'message': '该流程已审核，请勿重复点击！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.eventapprovalrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.eventapprovalrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.eventapprovalrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.eventapprovalrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.eventapprovalrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    next_audit_record = obj.eventapprovalrecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.eventapprovalrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    next_audit_record = obj.eventapprovalrecord_set.filter(node='five', state='unaudit').first()
                    obj_state = 'five'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.eventapprovalrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    obj_state = 'end'
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "工会活动审批"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class PreApprovalStopView(View):
    def post(self, request):
        flow_id = request.POST.get('id', '')
        types = request.POST.get('types', '')
        obj = EventApproval.objects.get(id=int(flow_id))
        if obj.state == 'end':
            returnData = {'code': 500, 'message': '操作失败，已完结流程无法操作！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.current_audit_users.clear()
        if types == 'stop':
            obj.state = 'stop'
            obj.save()
            returnData = {'code': 200, 'message': '终止成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            Topicsattachments.objects.filter(topics_number=obj.fj_number).delete()
            obj.eventapprovalrecord_set.all().delete()
            obj.audit_users_already.clear()
            obj.delete()
            returnData = {'code': 200, 'message': '删除成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class GoodsSubscribelListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'union_process/GoodsSubscribeList.html', {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = user.materialsapproval_set.all().order_by('-create_time')
        data_list = [{'id': obj.id, 'reason': obj.reason, 'goods_type': obj.goods_type, 'goods_number': obj.goods_number, 'total_amount': obj.total_amount,
                      'status': obj.get_state_str(), 'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='GoodsSubscribeDraft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
                      else f"<a href='GoodsSubscribeDetail.html?id={obj.id}'>查看</a> | <a href='GoodsSubscribeDetail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state not in ['draft', 'stop']
                      else f"<a href='GoodsSubscribeDetail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='GoodsSubscribeDetail.html?id={obj.id}'>查看</a>",
                      } for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class GoodsSubscribeIndexView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'union_process/GoodsSubscribeIndex.html', {'realname': real_name, 'position': position, 'department': department, "uuid": uuid.uuid4(), "create_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M")})

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        reason = request.POST.get("reason", "")           # 申请事由
        goods_type = request.POST.get("goods_type", "")             # 物资类型
        goods_number = request.POST.get("goods_number", "")       # 物资数量
        total_amount = request.POST.get("total_amount", "")       # 预算总金额
        money_capital = request.POST.get("money_capital", "")  # 金额大写
        note = request.POST.get("note", "")
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "工会物资申购")
        except:
            pass

        if flow_id:
            obj = MaterialsApproval.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.goods_type = goods_type
            obj.goods_number = goods_number
            obj.total_amount = total_amount
            obj.money_capital = money_capital
            obj.note = note
            obj.save()
            obj.current_audit_users.clear()
            obj.materialsapprovalrecord_set.filter(state='unaudit').delete()
            message_str = "修改成功"
        else:
            obj = MaterialsApproval.objects.create(apply_user=request.user, company=request.user.company, fj_number=fj_number, reason=reason, goods_type=goods_type, goods_number=goods_number, note=note, total_amount=total_amount, money_capital=money_capital)
            message_str = "创建成功"

        flag = True
        one_step = request.user.company.head_people
        if request.user != one_step:
            MaterialsApprovalRecord.objects.create(node='one', audit_note='', audit_people=one_step, parent_id=obj)
            obj.state = 'one'
            obj.current_audit_users.add(one_step)
            flag = False

        two_setp = request.user.company.leaders_id
        MaterialsApprovalRecord.objects.create(node='two', audit_note='', audit_people=two_setp, parent_id=obj)
        if flag:
            obj.state = 'two'
            obj.current_audit_users.add(two_setp)

        three_setp = Company.objects.get(id=7).head_people
        MaterialsApprovalRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=obj)

        four_setp = Staffing.objects.get(station='工会主席').post_personnel.all().first()
        MaterialsApprovalRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=obj)

        six_setp = Company.objects.get(id=7).head_people
        MaterialsApprovalRecord.objects.create(node='five', audit_note='', audit_people=six_setp, parent_id=obj)

        obj.save()
        returnDict = {'status': 'success', 'message': message_str, 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class GoodsSubscribeDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        obj = MaterialsApproval.objects.get(id=flow_id)
        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, "file_list": file_list, "create_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M")}
        return render(request, 'union_process/GoodsSubscribeDraft.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        reason = request.POST.get("reason", "")  # 申请事由
        goods_type = request.POST.get("goods_type", "")  # 物资类型
        goods_number = request.POST.get("goods_number", "")  # 物资数量
        total_amount = request.POST.get("total_amount", "")  # 预算总金额
        money_capital = request.POST.get("money_capital", "")  # 金额大写
        note = request.POST.get("note", "")
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "工会物资申购")
        except:
            pass

        if flow_id:
            obj = MaterialsApproval.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.goods_type = goods_type
            obj.goods_number = goods_number
            obj.total_amount = total_amount
            obj.money_capital = money_capital
            obj.note = note
            obj.save()
            message_str = "修改成功"
        else:
            obj = MaterialsApproval.objects.create(apply_user=request.user, company=request.user.company, fj_number=fj_number, reason=reason, goods_type=goods_type, goods_number=goods_number, note=note, total_amount=total_amount, money_capital=money_capital)
            message_str = "创建成功"

        obj.state = 'draft'
        obj.save()
        returnDict = {'status': 'success', 'message': message_str, 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class GoodsSubscribeDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = MaterialsApproval.objects.get(id=flow_id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.materialsapprovalrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.materialsapprovalrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                     'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                     'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_type": atta_obj.file_type,
                      "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (obj.state == 'refuse' and obj.apply_user == request.user) or revise else 'false', 'flow_dict': flow_dict, "revise": revise,
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user == obj.apply_user else 'false',
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'union_process/GoodsSubscribeDetail.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "工会物资申购")
        except:
            pass
        obj = MaterialsApproval.objects.get(id=int(flow_id))

        if not obj.materialsapprovalrecord_set.filter(node=obj.state, state='unaudit', audit_people=request.user).count():
            returnData = {'code': 400, 'message': '该流程已审核，请勿重复点击！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.materialsapprovalrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.materialsapprovalrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.materialsapprovalrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.materialsapprovalrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.materialsapprovalrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    next_audit_record = obj.materialsapprovalrecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.materialsapprovalrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    next_audit_record = obj.materialsapprovalrecord_set.filter(node='five', state='unaudit').first()
                    obj_state = 'five'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.materialsapprovalrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    obj_state = 'end'
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "工会物资申购"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class GoodsSubscribeStopView(View):
    def post(self, request):
        flow_id = request.POST.get('id', '')
        types = request.POST.get('types', '')
        obj = MaterialsApproval.objects.get(id=int(flow_id))
        if obj.state == 'end':
            returnData = {'code': 500, 'message': '操作失败，已完结流程无法操作！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.current_audit_users.clear()
        if types == 'stop':
            obj.state = 'stop'
            obj.save()
            returnData = {'code': 200, 'message': '终止成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            Topicsattachments.objects.filter(topics_number=obj.fj_number).delete()
            obj.materialsapprovalrecord_set.all().delete()
            obj.audit_users_already.clear()
            obj.delete()
            returnData = {'code': 200, 'message': '删除成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class SchedulingAdjustmentListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name}
        return render(request, 'union_process/SchedulingAdjustmentList.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = user.outpatientscheduling_set.all().order_by('-create_time')
        data_list = [{'id': obj.id, 'stop_reason': obj.stop_reason, 'person': obj.stop_patient if obj.scheduling_type in ["1", "2", "3"] else obj.change_patient,
                      'start_time': obj.stop_start_time if obj.scheduling_type in ["1", "2", "3"] else obj.patient_start_time,
                      'end_time': obj.stop_end_time if obj.scheduling_type in ["1", "2", "3"] else obj.patient_end_time,
                      'status': obj.get_state_str(), 'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='SchedulingAdjustmentDraft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
                      else f"<a href='SchedulingAdjustmentDetail.html?id={obj.id}'>查看</a> | <a href='SchedulingAdjustmentDetail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state not in ['draft', 'stop']
                      else f"<a href='SchedulingAdjustmentDetail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='SchedulingAdjustmentDetail.html?id={obj.id}'>查看</a>",
                      } for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SchedulingAdjustmentIndexView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "fj_number": uuid.uuid4(),
                   "create_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), "telephone": request.user.mobile}
        return render(request, 'union_process/SchedulingAdjustmentIndex.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        stop_reason = request.POST.get("stop_reason", "")  # 申请原因
        scheduling_type = request.POST.get("scheduling_type", "")  # 排班类型
        stop_patient = request.POST.get("stop_patient", "")  # 停诊人
        technical = request.POST.get("technical", "")  # 停诊人职称
        stop_start_time = request.POST.get("stop_start_time", "")  # 停诊开始时间
        stop_end_time = request.POST.get("stop_end_time", "")  # 停诊结束时间
        change_patient = request.POST.get("change_patient", "")  # 换诊人
        patient_technical = request.POST.get("patient_technical", "")  # 换诊人职称
        patient_start_time = request.POST.get("patient_start_time", "")  # 换诊开始时间
        patient_end_time = request.POST.get("patient_end_time", "")  # 换诊结束时间
        telephone = request.POST.get("telephone", "")  # 联系电话
        note = request.POST.get("note", "")

        if flow_id:
            obj = OutpatientScheduling.objects.get(id=int(flow_id))
            obj.stop_reason = stop_reason
            obj.telephone = telephone
            obj.scheduling_type = scheduling_type
            obj.stop_patient = stop_patient
            obj.technical = technical
            obj.stop_start_time = stop_start_time
            obj.stop_end_time = stop_end_time
            obj.change_patient = change_patient
            obj.patient_technical = patient_technical
            obj.patient_start_time = patient_start_time
            obj.patient_end_time = patient_end_time
            obj.note = note
            obj.save()
            obj.current_audit_users.clear()
        else:
            obj = OutpatientScheduling.objects.create(apply_user=request.user, company=request.user.company, fj_number=fj_number, stop_reason=stop_reason, scheduling_type=scheduling_type,
                                                      stop_patient=stop_patient, note=note, technical=technical, stop_start_time=stop_start_time, stop_end_time=stop_end_time, telephone=telephone,
                                                      change_patient=change_patient, patient_technical=patient_technical, patient_start_time=patient_start_time, patient_end_time=patient_end_time)

        flag = True
        one_step = request.user.company.head_people
        if request.user != one_step:
            OutpatientSchedulingRecord.objects.create(node='one', audit_note='', audit_people=one_step, parent_id=obj)
            obj.state = 'one'
            obj.current_audit_users.add(one_step)
            flag = False

        two_setp = Company.objects.get(id=25).head_people
        OutpatientSchedulingRecord.objects.create(node='two', audit_note='', audit_people=two_setp, parent_id=obj)
        if flag:
            obj.state = 'two'
            obj.current_audit_users.add(two_setp)

        obj.save()
        returnDict = {'status': 'success', 'message': "操作成功！", 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SchedulingAdjustmentDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        obj = OutpatientScheduling.objects.get(id=flow_id)
        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, "file_list": file_list, "create_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M")}
        return render(request, 'union_process/SchedulingAdjustmentDraft.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        stop_reason = request.POST.get("stop_reason", "")  # 申请原因
        scheduling_type = request.POST.get("scheduling_type", "")  # 排班类型
        stop_patient = request.POST.get("stop_patient", "")  # 停诊人
        technical = request.POST.get("technical", "")  # 停诊人职称
        stop_start_time = request.POST.get("stop_start_time", "")  # 停诊开始时间
        stop_end_time = request.POST.get("stop_end_time", "")  # 停诊结束时间
        change_patient = request.POST.get("change_patient", "")  # 换诊人
        patient_technical = request.POST.get("patient_technical", "")  # 换诊人职称
        patient_start_time = request.POST.get("patient_start_time", "")  # 换诊开始时间
        patient_end_time = request.POST.get("patient_end_time", "")  # 换诊结束时间
        telephone = request.POST.get("telephone", "")  # 联系电话
        note = request.POST.get("note", "")

        if flow_id:
            obj = OutpatientScheduling.objects.get(id=int(flow_id))
            obj.stop_reason = stop_reason
            obj.telephone = telephone
            obj.scheduling_type = scheduling_type
            obj.stop_patient = stop_patient
            obj.technical = technical
            obj.stop_start_time = stop_start_time
            obj.stop_end_time = stop_end_time
            obj.change_patient = change_patient
            obj.patient_technical = patient_technical
            obj.patient_start_time = patient_start_time
            obj.patient_end_time = patient_end_time
            obj.note = note
            obj.save()
        else:
            obj = OutpatientScheduling.objects.create(apply_user=request.user, company=request.user.company, fj_number=fj_number, stop_reason=stop_reason, scheduling_type=scheduling_type,
                                                      stop_patient=stop_patient, note=note, technical=technical, stop_start_time=stop_start_time, stop_end_time=stop_end_time, change_patient=change_patient,
                                                      patient_technical=patient_technical, patient_start_time=patient_start_time, patient_end_time=patient_end_time, telephone=telephone)

        obj.state = 'draft'
        obj.save()
        returnDict = {'status': 'success', 'message': "保存成功", 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SchedulingAdjustmentDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = OutpatientScheduling.objects.get(id=flow_id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.outpatientschedulingrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.outpatientschedulingrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_type": atta_obj.file_type,
                      "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (obj.state == 'refuse' and obj.apply_user == request.user) or revise else 'false', 'flow_dict': flow_dict, "revise": revise,
                   'is_audit': 'true' if obj.state in ['one', 'two'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'refuse'] and request.user == obj.apply_user else 'false',
                   'person': obj.stop_patient if obj.scheduling_type in ["1", "2", "3"] else obj.change_patient,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'union_process/SchedulingAdjustmentDetail.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "门诊排班调整")
        except:
            pass
        obj = OutpatientScheduling.objects.get(id=int(flow_id))

        if not obj.outpatientschedulingrecord_set.filter(node=obj.state, state='unaudit', audit_people=request.user).count():
            returnData = {'code': 400, 'message': '该流程已审核，请勿重复点击！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.outpatientschedulingrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.outpatientschedulingrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.outpatientschedulingrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                if state == 'audit':
                    obj_state = 'end'
                else:
                    obj_state = 'refuse'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "门诊排班调整"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.stop_reason[:15] + "……" if len(obj.stop_reason) > 15 else obj.stop_reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class SchedulingAdjustmentStopView(View):
    def post(self, request):
        flow_id = request.POST.get('id', '')
        types = request.POST.get('types', '')
        obj = OutpatientScheduling.objects.get(id=int(flow_id))
        if obj.state == 'end':
            returnData = {'code': 500, 'message': '操作失败，已完结流程无法操作！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.current_audit_users.clear()
        if types == 'stop':
            obj.state = 'stop'
            obj.save()
            returnData = {'code': 200, 'message': '终止成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            Topicsattachments.objects.filter(topics_number=obj.fj_number).delete()
            obj.outpatientschedulingrecord_set.all().delete()
            obj.audit_users_already.clear()
            obj.delete()
            returnData = {'code': 200, 'message': '删除成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")